import 'dart:io';

import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:flutter_document_picker/flutter_document_picker.dart';
import 'package:image_picker/image_picker.dart';
import 'package:smart_shop/model/shop_type.dart';
import 'package:smart_shop/utils/colorUtils.dart';
import 'package:smart_shop/utils/wheel_switch.dart';

/// 商家申请
class ShopApply extends StatefulWidget {
  const ShopApply({Key? key}) : super(key: key);

  @override
  State<ShopApply> createState() => _ShopApplyState();
}

class _ShopApplyState extends State<ShopApply> {
  late ScrollController _controller;

  late int type = 1;

  late String name = '';

  late String introduce = '';

  late List<ShopType> types = [];

  late List<int> selected = [];

  late List<String> imgs = [];

  @override
  void initState() {
    super.initState();
    _controller = ScrollController();
    types.add(ShopType('打扫·钟点工', 1));
    types.add(ShopType('家电清洗', 2));
    types.add(ShopType('做饭', 3));
    types.add(ShopType('月嫂', 4));
    types.add(ShopType('接送孩子', 5));
    types.add(ShopType('照顾老人/伤病人员', 6));
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: BrnAppBar(
          leading: GestureDetector(
            child: Icon(Icons.arrow_back, color: ColorUtils.fromHex('#212121')),
            onTap: () {
              Navigator.of(context).pop();
            },
          ),
          automaticallyImplyLeading: false,
          titleAlignment: Alignment.centerLeft,
          title: Container(
              alignment: Alignment.centerLeft,
              child: Text('申请新商铺/公司',
                  style: TextStyle(
                      fontSize: 18,
                      fontFamily: 'Source Han Sans CN',
                      color: ColorUtils.fromHex('#212121'),
                      fontWeight: FontWeight.w500))),
          primary: true,
          backgroundColor: Colors.white),
      body: Scrollbar(
        controller: _controller,
        child: SingleChildScrollView(
          primary: true,
          physics: const BouncingScrollPhysics(),
          padding: const EdgeInsets.all(10),
          child: Container(
            color: ColorUtils.fromHex('#F7F7F9'),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(
                  height: 40,
                  child: Row(
                    children: [
                      Flexible(
                        child: Align(
                          alignment: Alignment.center,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Radio<int>(
                                  value: 1,
                                  groupValue: type,
                                  activeColor: ColorUtils.fromHex('#6B8EF6'),
                                  onChanged: (int? value) {
                                    setState(() {
                                      type = value!;
                                    });
                                  }),
                              Text(
                                '家政公司',
                                style: TextStyle(
                                    fontFamily: 'Source Han Sans CN',
                                    fontWeight: FontWeight.normal,
                                    fontSize: 18,
                                    color: ColorUtils.fromHex('#1D1D2E')),
                              )
                            ],
                          ),
                        ),
                      ),
                      Flexible(
                          child: Align(
                        alignment: Alignment.center,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Radio<int>(
                                value: 2,
                                groupValue: type,
                                activeColor: ColorUtils.fromHex('#6B8EF6'),
                                onChanged: (int? value) {
                                  setState(() {
                                    type = value!;
                                  });
                                }),
                            Text(
                              '普通商铺',
                              style: TextStyle(
                                  fontFamily: 'Source Han Sans CN',
                                  fontWeight: FontWeight.normal,
                                  fontSize: 18,
                                  color: ColorUtils.fromHex('#1D1D2E')),
                            )
                          ],
                        ),
                      ))
                    ],
                  ),
                ),
                SizedBox(
                  height: 40,
                  child: Center(
                    child: Text('名称',
                        style: TextStyle(
                            fontFamily: 'Source Han Sans CN',
                            fontWeight: FontWeight.normal,
                            fontSize: 18,
                            color: ColorUtils.fromHex('#002440'))),
                  ),
                ),
                Container(
                  color: Colors.white,
                  child: TextField(
                    controller: TextEditingController()..text = name,
                    textAlignVertical: TextAlignVertical.center,
                    textDirection: TextDirection.ltr,
                    style: TextStyle(
                        fontFamily: 'Source Han Sans CN',
                        fontWeight: FontWeight.normal,
                        fontSize: 14,
                        color: ColorUtils.fromHex('#002440')),
                    decoration: InputDecoration(
                        hintText: '请输入',
                        hintStyle: TextStyle(
                            fontFamily: 'Source Han Sans CN',
                            fontSize: 14,
                            color: ColorUtils.fromHex('#B2B2B2'),
                            fontWeight: FontWeight.normal),
                        border: const OutlineInputBorder(
                            borderRadius:
                                BorderRadius.all(Radius.circular(6.0)),
                            borderSide: BorderSide(
                                color: Color.fromRGBO(54, 54, 90, 0.3))),
                        focusedBorder: const OutlineInputBorder(
                            borderSide: BorderSide(
                                color: Color.fromRGBO(54, 54, 90, 0.3)))),
                    onChanged: (String value) {
                      setState(() {
                        name = value;
                      });
                    },
                  ),
                ),
                SizedBox(
                  height: 40,
                  child: Align(
                    child: Text('简介',
                        style: TextStyle(
                            fontFamily: 'Source Han Sans CN',
                            fontWeight: FontWeight.normal,
                            fontSize: 18,
                            color: ColorUtils.fromHex('#002440'))),
                  ),
                ),
                Container(
                  color: Colors.white,
                  margin: const EdgeInsets.only(bottom: 10),
                  child: TextField(
                    controller: TextEditingController()..text = introduce,
                    obscureText: false,
                    maxLines: 5,
                    keyboardType: TextInputType.text,
                    textAlignVertical: TextAlignVertical.center,
                    textDirection: TextDirection.ltr,
                    style: TextStyle(
                        fontFamily: 'Source Han Sans CN',
                        fontWeight: FontWeight.normal,
                        fontSize: 14,
                        color: ColorUtils.fromHex('#002440')),
                    decoration: InputDecoration(
                        hintText: '请输入',
                        hintStyle: TextStyle(
                            fontFamily: 'Source Han Sans CN',
                            fontSize: 14,
                            color: ColorUtils.fromHex('#B2B2B2'),
                            fontWeight: FontWeight.normal),
                        border: const OutlineInputBorder(
                            borderRadius:
                                BorderRadius.all(Radius.circular(6.0)),
                            borderSide: BorderSide(
                                color: Color.fromRGBO(54, 54, 90, 0.3))),
                        focusedBorder: const OutlineInputBorder(
                            borderSide: BorderSide(
                                color: Color.fromRGBO(54, 54, 90, 0.3)))),
                    onChanged: (String value) {
                      setState(() {
                        introduce = value;
                      });
                    },
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 30),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: createWidget(context),
                  ),
                ),
                Container(
                  height: 40,
                  alignment: Alignment.center,
                  margin: const EdgeInsets.only(top: 10),
                  child: Text('相关资质：',
                      style: TextStyle(
                          fontFamily: 'PingFangSC-Regular',
                          fontWeight: FontWeight.normal,
                          fontSize: 18,
                          color: ColorUtils.fromHex('#002440'))),
                ),
                Container(
                    padding: const EdgeInsets.all(10),
                    decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius:
                            const BorderRadius.all(Radius.circular(6)),
                        border: Border.all(
                            color: const Color.fromRGBO(54, 54, 90, 0.03))),
                    child: Container(
                      color: Colors.white,
                      alignment: Alignment.center,
                      child: Wrap(
                        direction: Axis.horizontal,
                        alignment: WrapAlignment.center,
                        runAlignment: WrapAlignment.center,
                        spacing: 10,
                        runSpacing: 15,
                        children: [
                          ...uploadImg(context),
                          uploadBoxSize(context)
                        ],
                      ),
                    )),
                Container(
                  height: 40,
                  alignment: Alignment.center,
                  child: Text(
                    '服务小区：',
                    style: TextStyle(
                        fontFamily: 'PingFangSC-Regular',
                        fontWeight: FontWeight.normal,
                        fontSize: 18,
                        color: ColorUtils.fromHex('#002440')),
                  ),
                ),
                Container(
                  alignment: Alignment.center,
                  child: MaterialButton(
                      onPressed: () {},
                      height: 48,
                      minWidth: 190,
                      color: ColorUtils.fromHex('#3D7EFE'),
                      shape: const RoundedRectangleBorder(
                          side: BorderSide.none,
                          borderRadius: BorderRadius.all(Radius.circular(5))),
                      child: const Text(
                        '服务小区',
                        style: TextStyle(
                            color: Colors.white,
                            fontSize: 18,
                            fontWeight: FontWeight.normal,
                            fontFamily: 'PingFangSC-Regular'),
                      )),
                )
              ],
            ),
          ),
        ),
      ),
      bottomNavigationBar: Container(
        height: 68,
        color: Colors.white,
        alignment: Alignment.center,
        child: MaterialButton(
            onPressed: () {
              Navigator.of(context).pop();
            },
            height: 48,
            minWidth: 117,
            color: ColorUtils.fromHex('#3D7EFE'),
            shape: const RoundedRectangleBorder(
                side: BorderSide.none,
                borderRadius: BorderRadius.all(Radius.circular(5))),
            child: const Text(
              '申请',
              style: TextStyle(
                  color: Colors.white,
                  fontSize: 18,
                  fontWeight: FontWeight.normal,
                  fontFamily: 'PingFangSC-Regular'),
            )),
      ),
    );
  }

  List<Row> createWidget(BuildContext context) {
    return types
        .asMap()
        .map((i, e) {
          return MapEntry(
              i,
              Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    e.name,
                    style: TextStyle(
                        fontFamily: 'PingFangSC-Medium',
                        fontWeight: FontWeight.normal,
                        fontSize: 14,
                        color: ColorUtils.fromHex('#1D1D2E')),
                  ),
                  Container(
                    margin: const EdgeInsets.only(bottom: 10),
                    child: WheelSwitch(
                      value: selected.contains(e.value),
                      duration: const Duration(milliseconds: 100),
                      width: 60,
                      height: 40,
                      activeText: '',
                      inactiveText: '',
                      onChanged: (bool value) {
                        setState(() {
                          if (value) {
                            selected.add(e.value);
                          } else {
                            selected.remove(e.value);
                          }
                        });
                      },
                    ),
                  )
                ],
              ));
        })
        .values
        .toList();
  }

  List<Widget> uploadImg(BuildContext context) {
    return imgs.map((e) {
      return GestureDetector(
        child: Stack(
          children: [
            SizedBox(
              width: 80,
              height: 80,
              child: Image(
                image: FileImage(File(e)),
                fit: BoxFit.cover,
              ),
            ),
            const Positioned(
                top: 0,
                right: 0,
                width: 30,
                height: 30,
                child: Align(
                  alignment: Alignment.topRight,
                  child: Icon(Icons.delete, size: 20, color: Colors.redAccent),
                ))
          ],
        ),
        onTap: () {
          setState(() {
            imgs.remove(e);
          });
        },
      );
    }).toList();
  }

  Widget uploadBoxSize(BuildContext context) {
    return GestureDetector(
      child: SizedBox(
        width: 80,
        height: 80,
        child: Container(
          color: ColorUtils.fromHex('#B2B2B2'),
          child: const Align(
            child: Icon(Icons.add, size: 40, color: Colors.white),
          ),
        ),
      ),
      onTap: () async {
        await getImage();
      },
    );
  }

  /// 文件选取
  Future<void> getDocument() async {
    FlutterDocumentPickerParams? params = FlutterDocumentPickerParams(
      // 允许选取的文件拓展类型，不加此属性则默认支持所有类型
      allowedFileExtensions: [
        'pdf',
        'xls',
        'xlsx',
        'jpg',
        'png',
        'jpeg',
        'webp'
      ],
    );

    String? path = await FlutterDocumentPicker.openDocument(
      params: params,
    );
    BrnToast.show('${path}', context);
  }

  /// 图片选取
  Future<void> getImage() async {
    XFile? file = await ImagePicker().pickImage(
      source: ImageSource.gallery, // 图库选择
    );

    /// 选取图片失败file为null，要注意判断下。
    /// 获取图片路径后可以上传到服务器上
    BrnToast.show('${file?.path}', context);
    if (file != null && file.path.isNotEmpty) {
      setState(() {
        imgs.add(file.path);
      });
    }
  }

  /// 视频选取
  Future<void> getVideo() async {
    XFile? file = await ImagePicker().pickVideo(
      source: ImageSource.camera, // 调用相机拍摄
    );
    BrnToast.show('${file?.path}', context);
  }
}
